package com.atguigu.gulimall.ssoserver.controller;

import com.sun.deploy.net.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
public class LoginController {


    @Autowired
    StringRedisTemplate redisTemplate;

    /**
     * 获取已登录的用户信息
     * @param token  请求地址中携带的令牌
     * @return
     */
    @GetMapping("/userInfo")
    @ResponseBody
    public String userInfo(@RequestParam("token")String token){
        // 根据请求地址中携带的令牌去redis中查询用户信息
        String sstr = redisTemplate.opsForValue().get(token);
        return sstr;
    }


    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url") String url, Model model,
                            @CookieValue(value = "sso_token",required = false) String sso_token){
        // 判断浏览器的cookie中是否有上一次登录留下的令牌信息
        if (!StringUtils.isEmpty(sso_token)){
            return "redirect:" + url + "?token=" + sso_token;//令牌存在，直接跳回原页面，并携带token
        }
        model.addAttribute("url",url);
        return "login";
    }

    @PostMapping("/doLogin")
    public String doLogin(@RequestParam("username") String username,
                          @RequestParam("password") String password,
                          @RequestParam("url") String url,
                          HttpServletResponse response){
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)){

            // 1、登录成功用户信息放到缓存
            String uuid = UUID.randomUUID().toString().replace("_", "");
            redisTemplate.opsForValue().set(uuid,username);
            // 给浏览器登录服务器域下加cookie
            Cookie sso_token = new Cookie("sso_token", uuid);// 时间浏览器存活时间
            response.addCookie(sso_token);
            return "redirect:" + url + "?token=" + uuid;
        }
        // 登录成功跳转，跳回到之前的页面
        return "login";
    }
}
